package org.vm.cmbcdirect.wechat.controller;


import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.vm.cmbcdirect.wechat.utils.SignUtil;
import org.vm.cmbcdirect.wechat.service.CoreService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * Created by mv on 2016/3/22.
 */
@Controller
public class CoreController {

    private final static Logger LOGGER = Logger.getLogger(CoreController.class);

    @RequestMapping(value="wechat",method=RequestMethod.GET)
    @ResponseBody
    public String coreServlet_get(Model model, @ModelAttribute("signature") String signature,
                                  @ModelAttribute("timestamp") String timestamp,
                                  @ModelAttribute("nonce") String nonce,
                                  @ModelAttribute("echostr") String echostr
    ){
        String responseStr = "";
        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
        if (SignUtil.checkSignature(signature, timestamp, nonce)) {
            responseStr = echostr;
        }
        return responseStr;
    }

    @RequestMapping(value="wechat",method=RequestMethod.POST)
    public void coreServlet_post(Model model, HttpServletRequest request, HttpServletResponse response){
        try {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");

            // 调用核心业务类接收消息、处理消息
            String respMessage = CoreService.processRequest(request);

            if (respMessage == null || respMessage.trim().equals(""))
                return;

            // 响应消息
            PrintWriter out = response.getWriter();
            out.print(respMessage);
            out.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}
